
const ENEMY_IMG_URL = '/images/plane/enemy.png';

define([
  'require', 'pool'
], function(require, pool) {
  'use strict';
  
  var _this = {};

  function init (app, container) {
    var self = _this;
    self.loading = true;
    self.container = container;
    self.enemyPoolName = 'ENEMY_POOL';
    self.enemyArr = [];
    self.enemySpeed = 5;
    self.attackCounter = 0;// 出击计数器
    self.attackSpeed = 2;// 每秒钟出击个数

    new PIXI.loaders.Loader()
      .add('enemyImg', ENEMY_IMG_URL)
      .load(function (loader, res) {
        self.enemyTex = PIXI.Texture.fromFrame('enemyImg');

        for (let i = 0; i < 10; i++) {
          var enemy = newEnemy();
          self.enemyArr.push(enemy);
          pool.put(self.enemyPoolName, enemy);
          container.addChild(enemy);
        }
        self.loading = false;
      });
  }

  function newEnemy () {
    var enemy = new PIXI.Sprite(_this.enemyTex);
    enemy.visible = false;
    enemy.anchor.set(0.5);
    enemy.scale.set(0.6);
    return enemy;
  }

  function recoverEnemy (enemy) {
    enemy.visible = false;
    pool.put(_this.enemyPoolName, enemy);
  }

  function update (delta) {
    if (_this.loading) return;
    _this.enemyArr.forEach(function (enemy) {
      if (!enemy.visible) return;

      enemy.position.y += _this.enemySpeed;
      if (enemy.position.y > _this.container.height + _this.enemyTex.height / 2) {
        enemy.visible = false;
        pool.put(_this.enemyPoolName, enemy);
      }
    });

    _this.attackCounter += delta;
    if (_this.attackCounter >= 60 / _this.attackSpeed) {
      _this.attackCounter = 0;
      attack();
    }
  }

  function attack () {
    if (_this.loading) return;
    var enemy = pool.get(_this.enemyPoolName);
    if (enemy == null) {
      enemy = newEnemy();
      _this.container.addChild(enemy);
      _this.enemyArr.push(enemy);
    }

    enemy.visible = true;
    enemy.position.x = Math.random() * (_this.container.width - _this.enemyTex.width) + _this.enemyTex.width / 2;
    enemy.position.y = -_this.enemyTex.height / 2;
  }

  return {
    init: init,
    update: update,
    attack: attack,
    recoverEnemy: recoverEnemy,
    data: _this,
  }

});